<template>
	<div v-loading="loading" class="box">
		<Details
			v-if="notEmpty(infoData)"
			v-model="infoData"
			ref="Details"
			:type="type"></Details>
		<div v-else class="contenter"></div>
		<div class="footer">
			<div></div>
			<div>
				<el-button
					@click="
						_toPage({
							path: '/quota/forecast',
						})
					">
					取消
				</el-button>
				<el-button type="primary" plain @click="save('save')">
					暂存
				</el-button>
				<el-button type="primary" @click="save()">提交</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	import Details from '../chunk/details/index.vue';
	import * as apis from '@/api/quota/forecast/edit/api.js';
	export default {
		name: 'ForecastEdit',
		components: { Details },
		data() {
			return {
				type: '',
				loading: true,
				infoData: {},
			};
		},
		provide() {
			return {
				// details_forecast: () => this.infoData,
			};
		},
		// watch: {
		//     infoData: {
		//         deep: true,
		//         handler(val) {
		//             console.log(val);
		//         },
		//     },
		// },
		computed: {
			calcSchemeId() {
				return this.$route.query.calcSchemeId;
			},
		},
		created() {
			if (this.calcSchemeId) {
				this.$route.meta.title = '修改额度测算';
				const obj = Object.assign({}, this.$route, {
					title: '修改额度测算',
				});
				this.$tab.updatePage(obj);
				this.type = 'update';
				this.getDetails(this.calcSchemeId);
			} else {
				this.$route.meta.title = '新增额度测算';
				const obj = Object.assign({}, this.$route);
				this.$tab.updatePage(obj);
				this.loading = false;
				this.initDetaultDetails();
			}
		},
		methods: {
			initDetaultDetails() {
				this.infoData = {
					productList: [
						{
							plan: {},
							insuranceList: [],
							maintenanceList: [],
							attachedDecorationList: [],
							feeList: [],
						},
					],
				};
			},
			getDetails(calcSchemeId) {
				apis?.Details(calcSchemeId)
					.then(res => {
						if (res.code == 200) {
							this.infoData = res.data;
							Reflect.deleteProperty(
								this.infoData,
								'contractTemplateList',
							);
						}
					})
					.finally(() => {
						this.loading = false;
					});
			},

			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
			// 将第一条数据的保险维保分配给其他熟路
			allot() {
				if (this.infoData?.productList?.length <= 1) return;
				let productListItem = this._.cloneDeep(
					this.infoData?.productList?.[0],
				);

				this.infoData.productList?.forEach((item, index) => {
					if (index >= 1) {
						//购买类型
						item.insuranceBuyType =
							productListItem.insuranceBuyType;
						//购买方式
						item.insuranceBuyModeType =
							productListItem.insuranceBuyModeType;
						//保险公司
						item.insuranceCompanyKey =
							productListItem.insuranceCompanyKey;
						//保险公司
						item.insuranceCompanyVal =
							productListItem.insuranceCompanyVal;
						//保险标准
						item.insuranceStandardType =
							productListItem.insuranceStandardType;
						// 保险列表
						item.insuranceConfList = this._.cloneDeep(
							productListItem.insuranceConfList,
						);

						// // 增值服务特约条款
						// item.addedServicesType =
						// 	productListItem.addedServicesType;
						// // 交强险测算金额
						// item.insuranceCompulsoryQuondamAmount =
						// 	productListItem.insuranceCompulsoryQuondamAmount;
						// // 本次交强险金额
						// item.insuranceCompulsoryCurrentAmount =
						// 	productListItem.insuranceCompulsoryCurrentAmount;
						// // 车船税测算金额
						// item.insuranceCarvesselQuondamAmount =
						// 	productListItem.insuranceCarvesselQuondamAmount;
						// // 本次车船税金额
						// item.insuranceCarvesselCurrentAmount =
						// 	productListItem.insuranceCarvesselCurrentAmount;
						// // 商业险测算金额
						// item.insuranceCommercialQuondamAmount =
						// 	this._.cloneDeep(
						// 		productListItem.insuranceCommercialQuondamAmount,
						// 	);
						// // 本次商业险金额
						// item.insuranceCommercialCurrentAmount =
						// 	this._.cloneDeep(
						// 		productListItem.insuranceCommercialCurrentAmount,
						// 	);
						// // 保险询价附件
						// item.insuranceConsultAccessory = this._.cloneDeep(
						// 	productListItem.insuranceConsultAccessory,
						// );
						// // 维保费用（月）
						// item.maintenancePrice = this._.cloneDeep(
						// 	productListItem.maintenancePrice,
						// );
						// 年行驶公里数
						item.maintenanceAnnualMileageKey = this._.cloneDeep(
							productListItem.maintenanceAnnualMileageKey,
						);
						// 是否包含维保
						item.maintenanceType = this._.cloneDeep(
							productListItem.maintenanceType,
						);
						// 供应商
						item.maintenanceSupplierId = this._.cloneDeep(
							productListItem.maintenanceSupplierId,
						);
						item.maintenanceSupplierName = this._.cloneDeep(
							productListItem.maintenanceSupplierName,
						);
						// 合同是否限制里程
						item.maintenanceMileageType = this._.cloneDeep(
							productListItem.maintenanceMileageType,
						);
						// 维保套餐
						item.maintenanceMealType = this._.cloneDeep(
							productListItem.maintenanceMealType,
						);
						// 维保套餐列表
						item.maintenanceList = this._.cloneDeep(
							productListItem.maintenanceList,
						);
						// // 维保费用合计：￥
						// item.maintenanceFee = this._.cloneDeep(
						// 	productListItem.maintenanceFee,
						// );
						// // 输入框状态快照
						// item.planConf = this._.cloneDeep(
						// 	productListItem.planConf,
						// );
					}
				});
			},
			async save(type) {
				try {
					this.allot();
					if (type !== 'save') {
						let computeRes = false;
						this.$modal.loading('正在重新测算中，请稍候...');
						try {
							computeRes = await this.$refs.Details.computeAll();
						} catch (error) {}
						this.$modal.closeLoading();
						if (computeRes !== true) return;
					}
					if (type !== 'save') {
						let result = await this.valid();
						if (!result) {
							this.scrollToError();
							this.$message({
								type: 'error',
								message: '请先完善表单！',
							});
							return;
						}
						// if (this.Empty(this.infoData?.quoterCalcParam)) {
						//     this.$emitter.emit("setQuoterCalcParam");
						// }
					} else {
						this.$refs.Details.getFormData('save');
					}

					this.$emitter.emit('setQuoterCalcParam'); // 设置测算参数
					this.$emitter.emit('setchangeState'); // 设置输入框是否更改

					let params = this.infoData;
					let methods, word;
					if (type == 'save') {
						methods = apis.DraftSave;
						word = '暂存';
					} else {
						methods = apis.Save;
						word = '提交';
					}
					this.$modal.loading('正在提交中，请稍候...');
					methods(params)
						.then(res => {
							if (res.code == 200) {
								this.$message({
									message: `${word}成功！`,
									type: 'success',
								});
								this.$tab.closeOpenPage(this.$route);
								this._toPage({
									name: 'Forecast',
									path: '/quota/forecast',
								});
							}
						})
						.finally(() => {
							this.$modal.closeLoading();
						});
				} catch (error) {
					console.log(error);
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.box {
		min-height: 100vh;
	}
	.contenter {
		min-height: 100vh;
	}
	.footer {
		margin: 20px;
		margin-top: 45px;
		padding: 15px 20px;
		background: #ffffff;
		border-radius: 8px;
		display: flex;
		justify-content: space-between;
		position: sticky;
		bottom: 50px;
		background: transparent;
		height: 0;
	}
</style>
